<template>
  <div class="Wrapper ">
    <div class="NavBox">
      <div class="logo">
        <img src="@/assets/img/logo.png" alt="logo" />
      </div>
      <el-menu background-color="#202033" text-color="rgba(255, 255, 255, .7)" active-text-color="#fff" :default-active="activeMenu" class="nav-menu" @select="handleSelect">
        <template v-for="menu in menuList" :key="menu.path">
          <!-- 没有子菜单的情况 -->
          <el-menu-item v-if="!menu.children && (!('show' in menu) || menu.show)" :index="menu.path">
            <!-- <el-icon><component :is="menu.icon" /></el-icon> -->
            <span>{{ menu.title }}</span>
          </el-menu-item>

          <!-- 有子菜单的情况 -->
          <el-sub-menu v-else-if="!('show' in menu) || menu.show" :index="menu.path">
            <template #title>
              <!-- <el-icon><component :is="menu.icon" /></el-icon> -->
              <span>{{ menu.title }}</span>
            </template>
            <el-menu-item v-for="subMenu in menu.children" :key="subMenu.path" :index="subMenu.path">
              {{ subMenu.title }}
            </el-menu-item>
          </el-sub-menu>
        </template>
      </el-menu>
    </div>

    <div class="ContentBox ">
      <div class="header">
        <div class="tabs-nav">
          <div v-for="tab in tabsList" :key="tab.path" :class="['tabsItem', { active: activeTab === tab.path }]" @click="handleTabClick(tab)">
            {{ tab.title }}
            <el-icon v-if="tab.path !== '/'" @click.stop="removeTab(tab.path)">
              <Close />
            </el-icon>
          </div>
        </div>
        <div class="user-info">
          <el-dropdown trigger="click">
            <div class="user">
              <el-avatar :size="40" :src="imgUrls(mainStore.userInfo.logo) || 'https://placeholder.com/40'" />
              <span class="username">{{ mainStore.userInfo.username }}</span>
              <el-icon class="el-icon--right"><CaretBottom /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      <div class="main-content ">
        <div class="content ">
          <router-view></router-view>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref, watch, computed, onMounted } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { imgUrls } from '@/utils/utils';
  import Http from '@/utils/http';
  import { HomeFilled, User, Document, List, Calendar, Search, Star, CaretBottom, Close } from '@element-plus/icons-vue';
  import { useMainStore } from '@/stores/useMain';
  import { useTabsStore } from '@/stores/useTabs';

  const mainStore = useMainStore();
  const tabsStore = useTabsStore();
  const route = useRoute();
  const router = useRouter();
  const activeMenu = ref(route.path);

  onMounted(() => {
    // 设置激活菜单为当前路径
    updateActiveMenu(route.path);

    // 初始化标签页，处理可能的持久化数据异常
    try {
      if (tabsStore.tabs && tabsStore.tabs.length > 0) {
        tabsList.value = tabsStore.tabs;
      }

      if (tabsStore.activeTabPath) {
        activeTab.value = tabsStore.activeTabPath;
      } else {
        // 如果没有激活的标签页，默认激活当前路径或首页
        activeTab.value = route.path || '/';
        tabsStore.setActiveTab(activeTab.value);
      }
    } catch (error) {
      console.error('初始化标签页出错:', error);
      // 出错时使用默认值
      tabsList.value = [{ title: '首页', path: '/', closable: false }];
      activeTab.value = '/';

      // 重置存储中的值
      tabsStore.clearTabs();
      tabsStore.setActiveTab('/');
    }

    // 获取用户信息
    Http.get({
      url: '/yp_admin/getUserInfo',
      params: {
        id: mainStore.userInfo.id,
      },
    })
      .then((res) => {
        // 统一处理未授权情况
        if (res.code == 401 || res.code == 201 || (res.code == 200 && !res.data.enabled)) {
          console.log('Unauthorized or disabled user, redirecting to login');
          mainStore.userInfo = {};
          mainStore.token = '';
          router.replace('/login');
          return;
        }

        // 处理其他错误情况
        if (res.code != 200) {
          ElMessage({
            message: res.msg,
            type: 'warning',
          });
          return;
        }

        // 成功情况
        console.log('User info updated successfully');
        mainStore.userInfo = res.data;
      })
      .catch((error) => {
        // 添加错误处理
        console.error('Failed to fetch user info:', error);
        mainStore.userInfo = {};
        mainStore.token = '';
        router.replace('/login');
      });
  });

  // 处理菜单选择
  const handleSelect = (index, indexPath) => {
    // 如果是子菜单项，需要拼接完整路径
    const parentMenu = menuList.value.find((menu) => menu.children?.some((child) => child.path === index));
    if (parentMenu) {
      router.push(`${parentMenu.path}/${index}`);
    } else {
      router.push(index);
    }
  };

  // 更新激活菜单的方法
  const updateActiveMenu = (path) => {
    // 如果是根路径
    if (path === '/') {
      activeMenu.value = path;
      return;
    }

    // 处理子路径，如 /backExam/arranged
    const segments = path.split('/').filter(Boolean);
    if (segments.length > 1) {
      // 如果是二级菜单，设置激活的是子菜单项
      activeMenu.value = segments[1];
    } else {
      // 如果是一级菜单，直接使用路径
      activeMenu.value = path;
    }
  };

  // 标签页相关的状态
  const activeTab = ref('/');
  const tabsList = ref([
    { title: '首页', path: '/', closable: false }, // 默认设置首页不可关闭
  ]);

  // 监听路由变化，动态添加标签页
  watch(
    () => route.path,
    (newPath) => {
      try {
        // 更新激活菜单
        updateActiveMenu(newPath);

        // 如果标签页已存在，只激活它
        if (tabsList.value.some((tab) => tab.path === newPath)) {
          activeTab.value = newPath;
          tabsStore.setActiveTab(newPath);
          return;
        }

        // 获取路由对应的标题
        const currentRoute = routeMap[newPath];
        if (currentRoute) {
          // 添加新标签页，除了首页外都可以关闭
          const newTab = {
            title: currentRoute.subTitle || currentRoute.title,
            path: newPath,
            closable: newPath !== '/', // 明确设置是否可关闭
          };
          tabsList.value.push(newTab);
          activeTab.value = newPath;
          tabsStore.addTab(newTab);
          tabsStore.setActiveTab(newPath);
        } else {
          console.warn(`未找到路径 ${newPath} 对应的路由配置，使用默认标题`);
          // 如果找不到对应的路由配置，使用默认标题
          const pathSegments = newPath.split('/');
          const defaultTitle = pathSegments[pathSegments.length - 1] || '未知页面';
          const newTab = {
            title: defaultTitle,
            path: newPath,
            closable: newPath !== '/',
          };
          tabsList.value.push(newTab);
          activeTab.value = newPath;
          tabsStore.addTab(newTab);
          tabsStore.setActiveTab(newPath);
        }
      } catch (error) {
        console.error('处理路由变化出错:', error);
        // 确保至少有首页标签
        if (tabsList.value.length === 0) {
          const homeTab = { title: '首页', path: '/', closable: false };
          tabsList.value.push(homeTab);
          activeTab.value = '/';
          tabsStore.addTab(homeTab);
          tabsStore.setActiveTab('/');
        }
      }
    },
  );

  // 修改处理标签页点击的方法
  const handleTabClick = (tab) => {
    activeTab.value = tab.path;
    tabsStore.setActiveTab(tab.path);
    router.push(tab.path);
  };

  // 处理标签页关闭
  const removeTab = (targetPath) => {
    // 首页不允许关闭
    if (targetPath === '/') return;

    // 找到要关闭的标签页的索引
    const tabs = tabsList.value;
    const activeTabPath = activeTab.value;
    const targetIndex = tabs.findIndex((tab) => tab.path === targetPath);

    if (targetIndex === -1) return;

    // 删除标签页
    tabs.splice(targetIndex, 1);
    tabsStore.removeTab(targetPath);

    // 如果关闭的是当前激活的标签页，需要激活其他标签页
    if (activeTabPath === targetPath) {
      // 默认激活左侧标签页，如果没有左侧标签页就激活右侧标签页
      const newActiveTab = tabs[targetIndex - 1] || tabs[targetIndex] || tabs[0];
      activeTab.value = newActiveTab.path;
      tabsStore.setActiveTab(newActiveTab.path);
      router.push(newActiveTab.path);
    }
  };

  // 模拟用户信息，实际应该从状态管理或API获取
  const userInfo = ref({
    username: '管理员',
    avatar: '',
  });

  const handleLogout = () => {
    // 清空用户信息和token
    mainStore.userInfo = {};
    mainStore.token = '';
    // 清空标签页状态
    tabsStore.clearTabs();
    // 重置路由，只保留登录页
    router.replace('/login');
  };

  // 路由映射表
  const routeMap = {
    '/': { title: '主页' },
    '/account': { title: '账号管理' },
    '/grading/institution': { title: '考级申报', subTitle: '考级机构' },
    '/grading/application': { title: '考级申报', subTitle: '考试申报' },
    '/registration': { title: '考级报名管理' },
    '/backExam/arrange': { title: '考级排考管理', subTitle: '排考场' },
    '/backExam/arranged': { title: '考级排考管理', subTitle: '已安排考场' },
    '/backExam/unarranged': { title: '考级排考管理', subTitle: '未安排考场' },
    '/score': { title: '考级成绩查询' },
    '/performance/org': { title: '展演', subTitle: '展演机构' },
    '/performance/manage': { title: '展演', subTitle: '展演管理' },

    '/performance/registration': { title: '展演', subTitle: '展演报名' },
  };

  // 菜单配置数据
  const menuList = computed(() => [
    {
      path: '/',
      title: '主页',
      icon: HomeFilled,
    },
    {
      path: '/account',
      title: '账号管理',
      icon: User,
      show: mainStore.userInfo.role?.roleType >= 80,
    },
    {
      path: '/grading',
      title: '考级申报',
      icon: Document,
      children: [
        {
          path: 'institution',
          title: '考级机构',
        },
        {
          path: 'application',
          title: '考试申报',
        },
      ],
    },
    {
      path: '/registration',
      title: '考级报名管理',
      icon: List,
    },
    {
      path: '/backExam',
      title: '考级排考管理',
      icon: Calendar,
      children: [
        {
          path: 'arrange',
          title: '排考场',
        },
        {
          path: 'arranged',
          title: '已安排考场',
        },
        {
          path: 'unarranged',
          title: '未安排考场',
        },
      ],
    },
    {
      path: '/score',
      title: '考级成绩查询',
      icon: Search,
    },
    // {
    //   path: '/performance',
    //   title: '展演',
    //   icon: Star,
    //   children: [
    //     {
    //       path: 'org',
    //       title: '展演机构',
    //     },
    //     {
    //       path: 'manage',
    //       title: '展演管理',
    //     },

    //     {
    //       path: 'registration',
    //       title: '展演报名',
    //     },
    //   ],
    // },
  ]);
</script>

<style scoped lang="scss">
  .Wrapper {
    width: 100vw;
    height: 100vh;
    background-color: #f2f2f2;
    overflow: hidden;
    display: flex;
    box-sizing: border-box;
    .NavBox {
      width: 200px;
      height: 100vh;
      background-color: #202033;

      .logo {
        height: 90px;
        padding: 10px;
        padding-top: 20px;
        padding-bottom: 20px;
        display: flex;
        justify-content: center;
        align-items: center;

        img {
          max-width: 100%;
          max-height: 100%;
          object-fit: contain;
          border-radius: 50%;
        }
      }

      .nav-menu {
        border-right: none;
        font-size: 15px;

        :deep(.el-sub-menu__title) {
          color: rgba(255, 255, 255, 0.7);
          font-size: 15px;

          &:hover {
            color: #fff;
            background-color: #2d2d48 !important;
          }
        }

        :deep(.el-menu-item) {
          font-size: 15px;

          &:hover {
            color: #fff;
            background-color: #2d2d48 !important;
          }

          &.is-active {
            color: #fff;
            background-color: #2d2d48 !important;
          }

          &::after,
          &::before {
            display: none !important;
          }

          // 移除边框
          border-left: none !important;

          // 添加这些样式来移除所有边框和点击效果
          &:focus,
          &:active {
            border: none !important;
            outline: none !important;
          }
        }

        // 移除子菜单的竖线
        :deep(.el-menu) {
          .el-menu-item {
            &::after,
            &::before {
              display: none !important;
            }
            border-left: none !important;
          }
        }
      }
    }
    .ContentBox {
      width: calc(100% - 200px); // 确保内容区域宽度固定为减去导航宽度的空间
      height: 100vh;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      padding: 10px 20px;
      box-sizing: border-box; // 确保padding包含在宽度内
      .header {
        min-height: 55px; // 设置最小高度
        height: 55px; // 设置固定高度
        background-color: #fff;
        box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
        display: flex;
        justify-content: space-between;
        align-items: center;
        // 修改内边距，使用固定值

        .tabs-nav {
          flex: 1;
          height: 100%;
          caret-color: transparent;
          display: flex;
          align-items: center;
          padding: 0 10px;
          overflow-x: auto;
          white-space: nowrap;

          &::-webkit-scrollbar {
            height: 4px;
          }

          &::-webkit-scrollbar-thumb {
            background-color: #dcdfe6;
            border-radius: 4px;
          }

          &::-webkit-scrollbar-track {
            background-color: #f6f6f6;
          }

          .tabsItem {
            height: 32px; // 设置标签固定高度
            padding: 0 15px; // 修改内边距
            border: 1px solid #d8dce5;
            display: flex;
            align-items: center;
            margin-right: 5px;
            border-radius: 4px;
            font-size: 14px;
            cursor: pointer;
            position: relative;
            transition: all 0.3s;

            // 关闭图标样式
            .el-icon {
              margin-left: 8px;
              width: 14px;
              height: 14px;
              color: #d8dce5;
              cursor: pointer;

              &:hover {
                color: #409eff;
              }
            }

            // 激活状态
            &.active {
              background-color: #ecf5ff;
              color: #409eff;
              border-color: #d9ecff;
              .el-icon {
                color: #409eff;
                cursor: pointer;
              }
            }

            // 悬停状态
            &:hover {
              color: #409eff;
              border-color: #c6e2ff;
              .el-icon {
                color: #409eff;
                cursor: pointer;
              }
            }
          }
        }

        .user-info {
          height: 100%;
          min-width: 150px; // 设置最小宽度，防止挤压
          padding-right: 10px;
          padding-left: 14px;
          border-left: 1px solid #f0f0f0;
          display: flex;
          align-items: center;
          cursor: pointer;

          .user {
            display: flex;
            align-items: center;

            .username {
              margin: 0 8px;
              font-size: 14px;
              color: #333;
            }
          }
        }
      }

      .main-content {
        height: calc(100% - 55px);
        width: 100%; // 确保宽度100%填充父容器
        background-color: #fff;
       
        margin-top: 20px;
        box-sizing: border-box;
        overflow: hidden; // 防止溢出

        .content {
          height:100%;
          width: 100%; // 确保宽度100%填充父容器
          padding: 20px;
          overflow-y: auto;
          box-sizing: border-box;
          position: relative;
        }
      }
    }
  }
</style>

<style lang="scss">
  // 重写菜单样式，提高优先级
  .el-menu.nav-menu {
    caret-color: transparent;

    .el-menu-item,
    .el-sub-menu__title {
      position: relative;
      caret-color: transparent;

      // 移除所有边框和点击效果
      &,
      &:hover,
      &:focus,
      &:active,
      &.is-active {
        border: 0 none !important;
        outline: 0 !important;
        -webkit-tap-highlight-color: transparent !important;
      }

      // 移除伪元素
      &::before,
      &::after {
        content: none !important;
        display: none !important;
        width: 0 !important;
        opacity: 0 !important;
        border: 0 none !important;
        background: transparent !important;
      }
    }

    // 处理子菜单
    .el-menu--inline {
      caret-color: transparent;

      .el-menu-item {
        caret-color: transparent;

        &,
        &:hover,
        &:focus,
        &:active,
        &.is-active {
          border: 0 none !important;
          outline: 0 !important;
        }

        &::before,
        &::after {
          content: none !important;
          display: none !important;
          width: 0 !important;
          opacity: 0 !important;
        }
      }
    }
  }

  // 移除菜单项的默认焦点样式
  .el-menu-item:focus {
    background-color: transparent !important;
  }

  // 确保活动状态下也没有边框
  .el-menu-item.is-active,
  .el-sub-menu.is-active > .el-sub-menu__title {
    &,
    &::before,
    &::after {
      border: 0 none !important;
      outline: 0 !important;
    }
  }

  // 添加全局标签页样式
  .el-tabs--card > .el-tabs__header .el-tabs__nav {
    border: none !important;
  }

  .el-tabs--card > .el-tabs__header .el-tabs__item {
    border: none !important;
    margin-right: 4px;
    // 移除过渡动画
    transition: none !important;

    &:first-child {
      border-left: none !important;
    }

    .el-icon-close {
      position: static;
      font-size: 12px;
      width: 14px;
      height: 14px;
      line-height: 14px;
      vertical-align: middle;
      margin-left: 6px;
      transform: none !important;
      transition: none !important;
    }
  }

  .el-tabs--card > .el-tabs__header {
    border-bottom: none;
  }

  // 全局样式覆盖
  .el-tabs--card {
    // 移除所有tabs相关的过渡动画
    * {
      transition: none !important;
    }

    > .el-tabs__header {
      border-bottom: none;

      .el-tabs__nav {
        border: none !important;
      }

      .el-tabs__item {
        border: none !important;
        margin-right: 4px;
        padding: 0 20px !important;

        // 移除所有状态的过渡动画
        &,
        &:hover,
        &:focus,
        &:active,
        &.is-active {
          transition: none !important;
        }

        // 修改关闭图标样式
        .el-icon-close {
          position: static;
          font-size: 12px;
          width: 14px;
          height: 14px;
          line-height: 14px;
          vertical-align: middle;
          margin-left: 6px;
          transform: none !important;
          transition: none !important;
          color: #909399 !important; // 设置固定颜色
          opacity: 1 !important; // 确保始终显示
          visibility: visible !important; // 确保始终可见

          // 只在hover时改变背景色
          &:hover {
            background-color: #909399;
            color: #fff !important;
            border-radius: 50%;
          }
        }

        // 移除hover时的关闭图标样式变化
        &:hover {
          .el-icon-close {
            color: #909399 !important;
          }
        }
      }
    }
  }

  // 确保没有任何动画效果
  .el-tabs__active-bar {
    display: none !important;
  }

  .el-tabs__nav-wrap::after {
    display: none !important;
  }
</style>
